import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';

import { getPSITokenId } from '../../../utils/tokenId';

import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
import Button from '@material-ui/core/Button';
import CloseIcon from '@material-ui/icons/Close';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import RightArrowIcon from '@material-ui/icons/KeyboardArrowRight'

import CustomerCategoryDialog from './CustomerCategoryDialog';
import WarehouseDialog from './WarehouseDialog';
import MsgBox from '../../../utils/msgbox';
import * as customerService from '../services/customerService';

const styles = {
  appBar: {
    position: 'static',
  },
  flex: {
    flex: 1,
  },
  form: {
    padding: 10,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
};

function Transition(props) {
  return <Slide direction="up" {...props} />;
}

class CustomerEditDialog extends React.Component {
  state = {
    anchorEl: null,
    selectedTab: 0,
    categoryDialogOpen: false,
    msgBoxOpen: false,
    msgBoxInfo: '',
    warehouseDialogOpen: false,
    id: '',
    warehouseId: '',
    warehouseName: '[无]',
    categoryId: '', code: '', name: '', address: '', addressReceipt: '',
    contact01: '', mobile01: '', tel01: '', qq01: '', contact02: '', mobile02: '',
    tel02: '', qq02: '',
    bankName: '', bankAccount: '', tax: '', fax: '', initReceivables: '',
    initReceivablesDT: '',
    note: ''
  }

  constructor(props) {
    super(props);

    if (!getPSITokenId()) {
      router.replace('/auth/login');
    }
  }

  tabChange = (event, value) => {
    this.setState({ selectedTab: value });
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { entity } = nextProps;
    const { id } = prevState;
    if (entity && id !== entity.id) {
      return {
        ...entity
      }
    }
    else {
      return null;
    }
  }


  render() {
    const { classes, open, add, onCancel, onOK, ...other } = this.props;
    const { selectedTab, categoryDialogOpen, categoryName, code, name, address, addressReceipt,
      contact01, mobile01, tel01, qq01, contact02, mobile02, tel02, qq02,
      bankName, bankAccount, tax, fax, initReceivables, initReceivablesDT,
      warehouseName, note, msgBoxInfo, msgBoxOpen, warehouseDialogOpen } = this.state;

    return (
      <Dialog fullScreen open={open} {...other} TransitionComponent={Transition}>
        <AppBar position='static'>
          <Toolbar>
            <IconButton className={classes.menuButton} onClick={onCancel}>
              <CloseIcon />
            </IconButton>
            <Typography style={{ flex: 1 }} variant="title" color="inherit">
              {add ? '新增客户资料' : '编辑客户资料'}
            </Typography>
            <Button color="inherit" onClick={this.onSave}>
              保存
            </Button>
          </Toolbar>
        </AppBar>

        <form className={classes.form}>
          <Tabs
            value={selectedTab}
            indicatorColor="primary"
            textColor="primary"
            onChange={this.tabChange}
          >
            <Tab label='主要' value={0}></Tab>
            <Tab label='联系人' value={1}></Tab>
            <Tab label='财务' value={2}></Tab>
            <Tab label='其他' value={3}></Tab>
          </Tabs>
          {
            selectedTab === 0 &&
            <div style={{ margin: 5 }}>
              <FormControl fullWidth margin="none">
                <InputLabel required>客户分类</InputLabel>
                <Input onClick={this.onCategoryClick}
                  value={categoryName} readOnly
                  endAdornment={
                    <InputAdornment position="end">
                      <IconButton
                        onClick={this.onCategoryClick}
                      >
                        <RightArrowIcon />
                      </IconButton>
                    </InputAdornment>
                  }
                />
              </FormControl>
              <TextField type='text' label='编码' fullWidth margin="none" required
                value={code} onChange={(e) => { this.setState({ code: e.target.value }) }} ></TextField>
              <TextField type='text' label='客户名称' fullWidth margin="none" required
                value={name} onChange={(e) => { this.setState({ name: e.target.value }) }}></TextField>
              <TextField type='text' label='地址' fullWidth margin="none"
                value={address} onChange={(e) => { this.setState({ address: e.target.value }) }}></TextField>
              <TextField type='text' label='收货地址' fullWidth margin="none"
                value={addressReceipt} onChange={(e) => { this.setState({ addressReceipt: e.target.value }) }}></TextField>
            </div>
          }
          {
            selectedTab === 1 &&
            <div style={{ margin: 5 }}>
              <TextField type='text' label='联系人' fullWidth margin="none"
                value={contact01} onChange={(e) => { this.setState({ contact01: e.target.value }) }}></TextField>
              <TextField type='text' label='手机' fullWidth margin="none"
                value={mobile01} onChange={(e) => { this.setState({ mobile01: e.target.value }) }}></TextField>
              <TextField type='text' label='固话' fullWidth margin="none"
                value={tel01} onChange={(e) => { this.setState({ tel01: e.target.value }) }}></TextField>
              <TextField type='text' label='QQ' fullWidth margin="none"
                value={qq01} onChange={(e) => { this.setState({ qq01: e.target.value }) }}></TextField>
              <TextField type='text' label='备用联系人' fullWidth margin="none"
                value={contact02} onChange={(e) => { this.setState({ contact02: e.target.value }) }}></TextField>
              <TextField type='text' label='备用手机' fullWidth margin="none"
                value={mobile02} onChange={(e) => { this.setState({ mobile02: e.target.value }) }}></TextField>
              <TextField type='text' label='备用固话' fullWidth margin="none"
                value={tel02} onChange={(e) => { this.setState({ tel02: e.target.value }) }}></TextField>
              <TextField type='text' label='备用QQ' fullWidth margin="none"
                value={qq02} onChange={(e) => { this.setState({ qq02: e.target.value }) }}></TextField>
            </div>
          }
          {
            selectedTab === 2 &&
            <div style={{ margin: 5 }}>
              <TextField type='text' label='开户行' fullWidth margin="none"
                value={bankName} onChange={(e) => { this.setState({ bankName: e.target.value }) }}></TextField>
              <TextField type='text' label='开户行账号' fullWidth margin="none"
                value={bankAccount} onChange={(e) => { this.setState({ bankAccount: e.target.value }) }}></TextField>
              <TextField type='text' label='税号' fullWidth margin="none"
                value={tax} onChange={(e) => { this.setState({ tax: e.target.value }) }}></TextField>
              <TextField type='text' label='传真' fullWidth margin="none"
                value={fax} onChange={(e) => { this.setState({ fax: e.target.value }) }}></TextField>
              <TextField type='number' label='期初余额' fullWidth margin="none"
                value={initReceivables} onChange={(e) => { this.setState({ initReceivables: e.target.value }) }}></TextField>
              <TextField type='date' label='期初余额日期' fullWidth margin="none"
                value={initReceivablesDT} onChange={(e) => { this.setState({ initReceivablesDT: e.target.value }) }}></TextField>
            </div>
          }
          {
            selectedTab === 3 &&
            <div style={{ margin: 5 }}>
              <FormControl fullWidth margin="none">
                <InputLabel>销售出库仓库</InputLabel>
                <Input onClick={this.onWarehouseClick}
                  value={warehouseName} readOnly
                  endAdornment={
                    <InputAdornment position="end">
                      <IconButton
                        onClick={this.onWarehouseClick}
                      >
                        <RightArrowIcon />
                      </IconButton>
                    </InputAdornment>
                  }
                />
              </FormControl>
              <TextField type='text' label='备注' fullWidth margin="none"
                value={note} onChange={(e) => { this.setState({ note: e.target.value }) }}></TextField>
            </div>
          }
        </form>

        <CustomerCategoryDialog open={categoryDialogOpen}
          onClose={() => { this.setState({ categoryDialogOpen: false }) }}
          onCategroySelect={this.onCategroySelect} />

        <MsgBox open={msgBoxOpen} info={msgBoxInfo}
          onOK={() => { this.setState({ msgBoxOpen: false }) }}>
        </MsgBox>

        <WarehouseDialog open={warehouseDialogOpen}
          onClose={() => { this.setState({ warehouseDialogOpen: false }) }}
          onWarehouseSelect={this.onWarehouseSelect} />
      </Dialog >
    );
  }

  onSave = () => {
    const { id, categoryId, code, name, address, addressReceipt,
      contact01, mobile01, tel01, qq01, contact02, mobile02, tel02, qq02,
      bankName, bankAccount, tax, fax, initReceivables, initReceivablesDT,
      warehouseId, note } = this.state;
    if (!categoryId) {
      this.setState({ msgBoxOpen: true, msgBoxInfo: '没有选择客户分类' });
      return;
    }
    if (!code) {
      this.setState({ msgBoxOpen: true, msgBoxInfo: '没有输入编码' });
      return;
    }
    if (!name) {
      this.setState({ msgBoxOpen: true, msgBoxInfo: '没有输入客户名称' });
      return;
    }

    const customer = {
      id, categoryId, code, name, address, addressReceipt,
      contact01, mobile01, tel01, qq01, contact02, mobile02, tel02, qq02,
      bankName, bankAccount, tax, fax, initReceivables, initReceivablesDT,
      warehouseId, note
    };

    const customerId = id;

    customerService.editCustomer(customer).then(
      ({ data: result }) => {
        if (result.success) {
          const { dispatch, onOK } = this.props;
          dispatch({ type: 'customerList/queryCustomerInfo', payload: { id: result.id } });
          if (!customerId) {
            // 新建
            router.push('/customer/detail');
          } else {
            onOK();
          }
        } else {
          // 显示错误信息
          this.setState({ msgBoxOpen: true, msgBoxInfo: result.msg });
        }
      }
    );
  }

  onCategoryClick = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'customerCategoryList/queryCategoryList', payload: {} });

    this.setState({ categoryDialogOpen: true });
  }

  onCategroySelect = ({ text, id }) => {
    this.setState({ categoryName: text, categoryId: id });
  }

  onWarehouseClick = () => {
    this.setState({ warehouseDialogOpen: true });
  }

  onWarehouseSelect = ({ text, id }) => {
    this.setState({ warehouseName: text, warehouseId: id });
  }
}

CustomerEditDialog.propTypes = {
};

function mapStateToProps(state) {
  const { entity } = state.customerList;

  return {
    entity, loading: state.loading.models.customerList
  };
}

export default connect(mapStateToProps)(withStyles(styles)(CustomerEditDialog));
